﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;

namespace CodeContrib.Web.Mvc.Unity
{
	public class UnityControllerFactory : DefaultControllerFactory
	{
		private readonly IUnityContainer _container;

		public UnityControllerFactory(IUnityContainer container)
		{
			Guard.NotNull(container, "container");

			_container = container;
		}

		protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
		{
			IController controller;

			if (controllerType == null)
			{
				throw new HttpException(404, string.Format("The controller for path '{0}' could not be found or does not implement IController.", requestContext.HttpContext.Request.Path));
			}

			if (!typeof (IController).IsAssignableFrom(controllerType))
			{
				throw new ArgumentException(string.Format("Type requested is not a controller: {0}.", controllerType.Name), "controllerType");
			}

			try
			{
				controller = _container.Resolve(controllerType) as IController;
			}
			catch (Exception exception)
			{
				throw new InvalidOperationException(string.Format("Error resolving controller {0}.", controllerType.Name), exception);
			}

			return controller;
		}

		public override void ReleaseController(IController controller)
		{
			_container.Teardown(controller);
		}
	}
}